using UnityEngine;
using UnityEngine.UI;

namespace Managers
{
    public class GameManager : MonoBehaviour
    {
        [SerializeField] private Text _scoreText;
        [SerializeField] private GameObject _pausePanel;
        [SerializeField] private StatisticManager _statisticManager;
        private int _score;
        private int _bestScore;
        private float _time;
        
        private void Start() => Utils.TryHideCursor();

        private void Update()
        {
            _time += Time.deltaTime * Time.timeScale;
            if (Input.GetKeyDown(KeyCode.Escape)) Pause();
            if (Input.GetKeyDown(KeyCode.R)) Restart();
        }

        public void QuitToMenu()
        {
            _statisticManager.IncreasePlayTime((int)_time);
            _statisticManager.SaveStatistic();
            LevelManager.SwitchToScene(0);
        }

        public void Pause()
        {
            Utils.TryShowCursor();
            Time.timeScale = 0f;
            _pausePanel.SetActive(true);
        }

        public void Continue()
        {
            Utils.TryHideCursor();
            Time.timeScale = 1f;
            _pausePanel.SetActive(false);
        }
        
        public void Restart()
        {
            _statisticManager.IncreasePlayTime((int)_time);
            _statisticManager.SaveStatistic();
            LevelManager.ReloadScene();
        }

        public void IncreaseScore()
        {
            _score += 1;
            _scoreText.text = $"Счет: <b>{_score}</b>";
            if (_score <= _bestScore) return;
            _bestScore = _score;
            _statisticManager.SetBestScore(_bestScore);
        }
    }
}
